package com.vacation.vacationdemo.realm;

import com.vacation.vacationdemo.entity.Permissions;
import com.vacation.vacationdemo.entity.Role;
import com.vacation.vacationdemo.service.LoginService;
import com.vacation.vacationdemo.vo.EmployeeVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * @author 杨光
 * @date 2022年03月12日 14:32
 */
public class VacationRealm extends AuthorizingRealm {

    @Autowired
    LoginService loginService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录用户名
        String empNo = (String) principals.getPrimaryPrincipal();
        //查询用户名称
        EmployeeVo employeeVo = loginService.selectEmployeeByEmpNo(empNo);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : employeeVo.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {

        //如果没有找到登录用户名，返回null，则shiro会抛异常
        if (StringUtils.isEmpty(token.getPrincipal())) {
            return null;
        }
        //获取登录账号
        String empNo = token.getPrincipal().toString();
        EmployeeVo employeeVo = loginService.selectEmployeeByEmpNo(empNo);
        if(employeeVo==null){
            return null;//如果返回null那么shiro会抛出异常
        }else{
            //把用户信息放入session
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("loginUser",employeeVo);

            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(empNo, employeeVo.getEmpPassword(), getName());
            return simpleAuthenticationInfo;
        }

    }
}
